<template>
  <div ref="chart" style="width:90%;height:190px;padding-top:10px;margin-left: 15px;"></div>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios';
import dayjs from 'dayjs';

export default {
  data() {
    return {
      chart: null,
      chartData: [],
      defaultDate: dayjs().format('YYYY-MM-DD') // 默认日期为当前日期
    };
  },
  mounted() {
    this.initChart();
    this.getData(this.defaultDate); // 获取数据时使用默认日期
  },
  methods: {
    async getData(date) {
      try {
        const res = await axios.get(`http://localhost:8080/data/user/age/`+date);
        this.chartData = res.data.data; // 假设返回的数据格式符合预期
        this.updateChart();
      } catch (err) {
        console.log('Failed to fetch data:', err);
      }
    },
    initChart() {
      // 初始化ECharts实例
      this.chart = echarts.init(this.$refs.chart);
      // 设置初始配置
      const option = this.getChartOption();
      this.chart.setOption(option);
    },
    updateChart() {
      // 更新图表数据
      const option = this.getChartOption();
      this.chart.setOption(option);
    },
    getChartOption() {
      return {
        legend: {
          top: 'bottom'
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        series: [
          {
            name: 'Nightingale Chart',
            type: 'pie',
            radius: [30, 85],
            center: ['50%', '50%'],
            roseType: 'area',
            itemStyle: {
              borderRadius: 8
            },
            data: this.chartData // 使用获取的数据
          }
        ]
      };
    }
  }
};
</script>

<style>
</style>
